<template>
  <div class="custom_video">
    <!-- 视频始终渲染（利用原生 poster 能力） -->
    <video ref="video" class="custom_video__video" :poster="props.poster" :src="props.src" autoplay muted playsinline
      loop @click="handleClick" @mousedown="handlePressStart" @mouseup="handlePressEnd" @mouseleave="handlePressEnd"
      @touchstart="handlePressStart" @touchend="handlePressEnd" @loadeddata="onLoadedData" @error="onError"></video>

    <!-- Loading 遮罩（最多显示 1.5 秒） -->
    <div v-if="loading" class="custom_video__loading"></div>

    <!-- 暂停图标（仅在非 loading 时显示） -->
    <div v-if="!loading" class="custom_video__pause" :class="{ show: pauseIcon }" @click="handleClick">
      <Icon name="zantingtubiao" size="35" color="#fff" />
    </div>

    <!-- 进度条（仅在非 loading 时显示） -->
    <div v-if="!loading && props.showProgress" class="videoCable">
      <div class="videoCable_line" :style="{ width: progress + '%' }">
        <div class="videoCable_dot"></div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onBeforeUnmount, nextTick, inject, onMounted } from 'vue'
import Icon from '@/components/Common/Icon/index.vue'

const userInteracted = inject('userInteracted', ref(false))
const props = defineProps({
  src: { type: String, default: '' },
  showProgress: { type: Boolean, default: true },
  active: { type: Boolean, default: false },
  poster: { type: String, default: '/images/default-video-poster.jpg' }, // 默认图兜底
})

const emit = defineEmits(['dbltap', 'load-error'])

const video = ref(null)
const loading = ref(true) // 控制 loading 和交互元素显示
const pauseIcon = ref(false)
const hasUnmuted = ref(false)
const progress = ref(0)

let loadTimeout = null
let pressTimer = null
let lastTapTime = 0
let isLongPress = false
let ignoreNextClick = false

// ========== 视频加载逻辑 ==========
watch(
  () => props.src,
  async (newSrc) => {
    if (!newSrc) {
      loading.value = false
      return
    }

    // 重置状态
    progress.value = 0
    hasUnmuted.value = false
    pauseIcon.value = false
    loading.value = true

    clearTimeout(loadTimeout)
    await nextTick()

    // ✅ 关键修改：超时时间从 5000ms 改为 1500ms
    loadTimeout = setTimeout(() => {
      if (loading.value) {
        loading.value = false // 超时后隐藏 loading，显示 poster
        emit('load-error')
      }
    }, 1500) // ←←← 1.5 秒

    video.value?.load()
  },
  { immediate: true }
)

// ========== active 切换控制播放/暂停 ==========
watch(() => props.active, (isActive) => {
  const vid = video.value
  if (!vid) return

  if (isActive) {
    if (userInteracted.value && !hasUnmuted.value) {
      vid.muted = false
      hasUnmuted.value = true
    }
    vid.play().catch(console.warn)
    pauseIcon.value = false
  } else {
    vid.pause()
    pauseIcon.value = true
  }
})

// ========== unmute 逻辑（保持不变）==========
watch(userInteracted, () => { attemptUnmute() })
watch(video, () => { attemptUnmute() })
onMounted(() => { attemptUnmute() })

const attemptUnmute = () => {
  const vid = video.value
  if (userInteracted.value && props.active && vid && vid.muted && !hasUnmuted.value) {
    vid.muted = false
    hasUnmuted.value = true
    if (vid.paused) {
      vid.play().catch(console.warn)
    }
  }
}

// ========== 进度更新 ==========
const updateProgress = () => {
  const vid = video.value
  progress.value = vid?.duration > 0 ? (vid.currentTime / vid.duration) * 100 : 0
}

const onLoadedData = () => {
  clearTimeout(loadTimeout)
  loading.value = false // 视频 ready，隐藏 loading
  video.value?.removeEventListener('timeupdate', updateProgress)
  video.value?.addEventListener('timeupdate', updateProgress)
}

const onError = () => {
  clearTimeout(loadTimeout)
  loading.value = false // 加载失败也隐藏 loading，显示 poster
  emit('load-error')
}

// ========== 清理 ==========
onBeforeUnmount(() => {
  video.value?.removeEventListener('timeupdate', updateProgress)
  clearTimeout(loadTimeout)
})

// ========== 用户交互（保持不变）==========
const togglePlayPause = () => {
  const vid = video.value
  if (!vid) return

  if (vid.paused) {
    if (userInteracted.value && !hasUnmuted.value) {
      vid.muted = false
      hasUnmuted.value = true
    }
    vid.play()
    pauseIcon.value = false
  } else {
    vid.pause()
    pauseIcon.value = true
  }
}

const handleClick = (e) => {
  if (!props.active) return
  if (ignoreNextClick) {
    ignoreNextClick = false
    return
  }

  const now = Date.now()
  if (now - lastTapTime < 300) {
    emit('dbltap')
    lastTapTime = 0
    return
  }

  lastTapTime = now
  setTimeout(() => {
    if (lastTapTime === now) togglePlayPause()
  }, 300)
}

const handlePressStart = () => {
  pauseIcon.value = false
  pressTimer = setTimeout(() => {
    isLongPress = true
    ignoreNextClick = true
    const vid = video.value
    if (vid) {
      if (vid.paused) {
        vid.play()
        vid.muted = false
        hasUnmuted.value = true
      }
      vid.playbackRate = 4
    }
  }, 300)
}

const handlePressEnd = () => {
  clearTimeout(pressTimer)
  if (isLongPress) {
    isLongPress = false
    video.value && (video.value.playbackRate = 1)
  }
}

// 暴露方法
defineExpose({
  play: () => {
    if (video.value) {
      video.value.play().catch(err => console.warn('CustomVideo.play() 被拒绝:', err))
    }
  },
  pause: () => {
    if (video.value) {
      video.value.pause()
    }
  },
  element: video
})
</script>

<style lang="scss" scoped>
.custom_video {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: #000;

  .custom_video__video {
    width: 100%;
    height: 100%;
    // object-fit: cover;
    display: block;
  }

  .custom_video__loading {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 25px;
    height: 25px;
    border: 2px solid transparent;
    border-bottom-color: #fff;
    border-radius: 50%;
    transform: translate(-50%, -50%);
    animation: loadingSpin 0.8s linear infinite;
    z-index: 99;
  }

  @keyframes loadingSpin {
    to {
      transform: translate(-50%, -50%) rotate(360deg);
    }
  }

  .custom_video__pause {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%) scale(0);
    color: #fff;
    z-index: 100;
    transition: transform 0.3s ease-out;

    &.show {
      transform: translate(-50%, -50%) scale(1);
    }
  }

  .videoCable {
    position: absolute;
    bottom: 52px;
    left: 50%;
    transform: translateX(-50%);
    width: 98%;
    height: 3px;
    background-color: #ccc;
    border-radius: 4px;
    z-index: 100;

    .videoCable_line {
      height: 100%;
      background-color: #fff;
      transition: width 0.1s linear;
      position: relative;

      .videoCable_dot {
        position: absolute;
        right: -2px;
        top: 50%;
        transform: translateY(-50%);
        width: 5px;
        height: 5px;
        border-radius: 50%;
        background-color: #fff;
      }
    }
  }
}
</style>